package cn.bluemobi.dylan.step.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bluemobi.dylan.step.R;
import cn.bluemobi.dylan.step.adapter.WeightRecordAdapter;
import cn.bluemobi.dylan.step.step.bean.StepData;
import cn.bluemobi.dylan.step.step.bean.Weight;
import cn.bluemobi.dylan.step.step.utils.DbUtils;
import cn.bluemobi.dylan.step.view.LineChartMarkView;

public class TiZhong extends AppCompatActivity {

    private Button recordBtn;
    private LineChart lineChart;
    private ImageView iv_left;
    //当天的日期
    private static String CURRENT_DATE = "";

    private Context mContext;
    private  List<Weight> weightList;
    private WeightRecordAdapter mAdapter;
    private ListView weightRecords;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ti_zhong);
        mContext = TiZhong.this;
        init();
        initData();
        initLineChart();
        showDialog();
    }
    private void init(){
        recordBtn=(Button) findViewById(R.id.weight_btn_record);
        lineChart=(LineChart) findViewById(R.id.chart);
        weightRecords=(ListView) findViewById(R.id.list);
        iv_left = (ImageView) findViewById(R.id.iv_left);
        iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        weightList = new ArrayList<>();
        weightList = DbUtils.getQueryLimit7(Weight.class,"id");
    }
    //将数据库体重加载到Listview
    private void initData(){
        mAdapter = new WeightRecordAdapter(mContext,weightList);
        weightRecords.setAdapter(mAdapter);
    }

    private void showDialog(){
        //加载自定义xml布局文件作为view对象
        final View view = LayoutInflater.from(mContext).inflate(R.layout.weight_dialog,null);
        //初始化builder
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setView(view);
        final AlertDialog dialog =builder.create();
        //体重保存到数据库，save按钮
        view.findViewById(R.id.weight_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editText = view.findViewById(R.id.weight_edit);
                String weightEdit = (String) editText.getText().toString();
                double weight = Double.valueOf(weightEdit.toString());
                if (weight < 10 || weight > 300) {
                    Toast toast = Toast.makeText(mContext, "请输入10-300之间的数字", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 180);
                    toast.show();

                } else {
                    CURRENT_DATE = getTodayDate();
                    List<Weight> list = DbUtils.getQueryByWhere(Weight.class, "date", new String[]{CURRENT_DATE});
                    if (list.size() == 0 || list.isEmpty()) {//没有这一天的体重记录
                        Weight newWeight = new Weight();
                        newWeight.setDate(CURRENT_DATE);
                        newWeight.setWeight(weightEdit);
                        DbUtils.insert(newWeight);
                        TiZhong.this.recreate();
                    } else if (list.size() == 1) {//有这一天的体重记录，更新
                        Weight newWeight = list.get(0);
                        newWeight.setWeight(weightEdit);
                        DbUtils.update(newWeight);
                        TiZhong.this.recreate();
                    } else {
                    }
                    dialog.dismiss();
                }
            }
        });

        //取消记录体重操作
        view.findViewById(R.id.weight_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        recordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });
    }

    /**
     * 获取当天日期
     *
     * @return
     */
    private String getTodayDate() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * 初始化图表数据
     */
    private void initLineChart(){
        // 不显示数据描述
        lineChart.getDescription().setEnabled(false);
        // 没有数据的时候，显示“暂无数据”
        lineChart.setNoDataText("暂无数据");
        // 不绘制网格背景
        lineChart.setDrawGridBackground(false);
        lineChart.setDragEnabled(true);//是否可以用手指移动图表
        lineChart.setTouchEnabled(true);
        lineChart.animateX(1500);
        lineChart.setDoubleTapToZoomEnabled(false);
        //禁止x轴y轴同时进行缩放
        lineChart.setPinchZoom(false);
        lineChart.setDragDecelerationEnabled(false);//拖拽滚动时，手放开是否会持续滚动，默认是true（false是拖到哪是哪，true拖拽之后还会有缓冲）
        lineChart.setDragDecelerationFrictionCoef(0.88f);//与上面那个属性配合，持续滚动时的速度快慢，[0,1) 0代表立即停止。
        // 不可以缩放
        lineChart.setScaleEnabled(false);
        setXAxis();
        setYAxis();
        setData();
    }




    /**
     * 设置Y轴数据
     */
    private void setYAxis(){
        YAxis yAxisLeft = lineChart.getAxisLeft();// 左边Y轴
        // 不显示y轴右边的值
        lineChart.getAxisRight().setEnabled(false);
        // 不从y轴发出横向直线
        yAxisLeft.setDrawGridLines(false);
        //y轴提供数据的区间个数5个  false:是否均匀显示数据
        yAxisLeft.setLabelCount(5,false);
        yAxisLeft.setTextColor(Color.BLACK);
        yAxisLeft.setTextSize(15f);
    }

    /**
     * 设置X轴数据
     */
    private void setXAxis() {
        final XAxis xAxis = lineChart.getXAxis();
        //将x轴的描述（文字 or 数字）显示在x轴下方
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //是否绘制x轴的网格线
        xAxis.setDrawGridLines(false);
        //是否绘制x轴的轴线
        xAxis.setDrawAxisLine(true);
        //设置颜色
        xAxis.setTextColor(Color.BLACK);
        xAxis.setTextSize(15f); // 文本大小为18dp
        xAxis.setGranularity(1f);

        xAxis.setLabelCount(weightList.size()); // 设置标签数量
        xAxis.setValueFormatter(new IndexAxisValueFormatter(){
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
                if(index<0||index>=weightList.size()){
                    return "";
                }else{
                    return weightList.get(weightList.size()-index-1).getDate().substring(5);
                }
            }
        });
    }

    /**
     * 填充数据
     */
    private void setData() {
        List<Entry> weightEntries = new ArrayList<>();
        float y = 0;
        for (int i = 0; i <weightList.size(); i++) {

            y = Float.valueOf(weightList.get(weightList.size()-i-1).getWeight()).floatValue();
            weightEntries.add(new Entry(i, y));
        }


        LineDataSet lineDataSet = new LineDataSet(weightEntries, "近七天体重折线");
        LineData lineData = new LineData(lineDataSet);
        lineData.setHighlightEnabled(true);
        lineChart.setData(lineData);
        LineChartMarkView markView = new LineChartMarkView(this,weightList,lineChart);
        lineChart.highlightValue(weightList.size(),0);
        lineChart.setMarker(markView);
        lineChart.invalidate();
        //设置折线的式样 :圆滑的曲线
        lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        lineDataSet.setColor(Color.BLACK);  //折线的颜色
        lineDataSet.setLineWidth(2);        //折线的粗细
        //是否画折线点上的空心圆  false表示直接画成实心圆
        lineDataSet.setDrawCircleHole(false);
        //lineDataSet.setCircleHoleRadius(3);  //空心圆的圆心半径
        //圆点的颜色
        lineDataSet.setCircleColor(Color.BLACK);
        lineDataSet.setCircleRadius(5);      //圆点的半径
        lineDataSet.setValueTextSize(12f);
    }

}